package org.jaaksi.demo.animator;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.view.View;
import android.widget.TextView;

/**
 * Created by Fcy on 2015/10/1.<br/>
 * 利用属性动画实现常见的 数字快速增减
 */
public class NumberAnimator extends Activity {

    private TextView textView;
    private int num = 300;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.animator_number);
        textView = (TextView) findViewById(R.id.textView);
        // 从服务器拿到数据后，设置并启动动画，这里使用本地数据模拟
        setTextSpan(num);
    }

    private void setTextSpan(int data) {
        String text = "距离北京奥运会开幕还有" + data + "天";
        SpannableStringBuilder builder = new SpannableStringBuilder(text);

        int began = "距离北京奥运会开幕还有".length();
        int end = began + String.valueOf(data).length();
        builder.setSpan(new ForegroundColorSpan(Color.RED), began, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        builder.setSpan(new StyleSpan(Typeface.BOLD), began, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        textView.setText(builder);
    }

    public void start(View view) {
        // 第二个参数为propertyName,如果不匹配，就是不管~~咱们只需要它按照时间插值和持续时间计算的那个值，我们自己手动调用addUpdateListener调节
        ObjectAnimator animator = ObjectAnimator.ofInt(textView, "numincreate", num, 0);
        animator.setDuration(1000 * 10);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                // 从ofInt中的start 和 end中在 duration 时间逐渐增加
                Integer value = (Integer) animation.getAnimatedValue("numincreate");
                setTextSpan(value);
            }
        });
        animator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                textView.setText("奥运会开始啦");
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        animator.start();
    }
}